import fs from 'fs';
import path from 'path';

export const mergeFile = (hash, ext) => {
  return new Promise((resolve, reject) => {

    const baseUrl = path.resolve('upload', `${hash}`)
    const createJson = path.resolve('upload', `${hash}.${ext}`)

    fs.readdir(baseUrl, function (err, files) {
      files.sort((a,b)=>{
        return a.replace(`${hash}-`, '') - b.replace(`${hash}-`, '')
      })
      console.log(files)
      if (err) {
        reject(err)
      }

      var fileReadStream;
      var fileWriteStream = fs.createWriteStream(createJson);
    
      createStramFile();

      function createStramFile() {
        if (!files.length) {
          resolve('ok')
          return;
        }
        var currentfile = baseUrl + '/' + files.shift();
        fileReadStream = fs.createReadStream(currentfile);
        fileReadStream.pipe(fileWriteStream, { end: files.length===0 });
        fileReadStream.on("end", function () {
          console.log(currentfile + ' appended');
          createStramFile();
        })
      }
    })
  })
}

export const deleteFolderRecursive = (path) => {
  if( fs.existsSync(path) ) {
    fs.readdirSync(path).forEach(function(file) {
      var curPath = path + "/" + file;
      if(fs.statSync(curPath).isDirectory()) { // recurse
        deleteFolderRecursive(curPath);
      } else { // delete file
        fs.unlinkSync(curPath);
      }
    })
    fs.rmdirSync(path);
  }
}